package com.fowo.api.sys.controller;

import com.fowo.api.common.model.IdListPo;
import com.fowo.api.common.model.R;
import com.fowo.api.sys.model.SysMenuBatchSetAppPo;
import com.fowo.api.user.model.JwtUserInfo;
import com.fowo.api.sys.entity.SysMenu;
import com.fowo.api.sys.model.CreateSysMenu;
import com.fowo.api.sys.model.SysMenuSearch;
import com.fowo.api.sys.model.SysMenuVo;
import com.fowo.api.sys.service.SysMenuService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@Tag(name = "系统菜单")
@RequestMapping("/api/sys/menu")
@RestController
public class SysMenuController {

    @Resource
    private SysMenuService menuService;

    @Operation(summary = "查询")
    @GetMapping()
    public R<List<SysMenuVo>> page(SysMenuSearch search) {
        return R.data(menuService.search(search));
    }

    @Operation(summary = "获取当前用户的菜单树")
    @GetMapping("my")
    public R<List<SysMenuVo>> my() {
        JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
        if (jwtUserInfo == null || jwtUserInfo.getUserId() == null || jwtUserInfo.getUserId() == 0L) {
            return R.fail("用户登录信息异常");
        }
        return R.data(menuService.getUserMenuTree(jwtUserInfo.getUserId()));
    }

    @Operation(summary = "获取指定 id 的记录")
    @GetMapping("{id}")
    public R<SysMenu> getById(@PathVariable Long id) {
        return R.data(menuService.getById(id));
    }

    @Operation(summary = "创建")
    @PostMapping
    public R<SysMenu> create(@Validated @RequestBody CreateSysMenu model) {
        return R.data(() -> menuService.create(model));
    }

    @Operation(summary = "更新")
    @PutMapping
    public R update(@Validated @RequestBody SysMenu sysMenu) {
        sysMenu.setBeeMakeAccess(0);
        return R.ok(() -> menuService.updateById(sysMenu));
    }

    @Operation(summary = "删除")
    @DeleteMapping("{id}")
    public R deleteById(@PathVariable Long id) {
        return R.run(() -> menuService.removeById(id));
    }

    @Operation(summary = "批量删除")
    @DeleteMapping("batch")
    public R deleteByIds(@RequestBody IdListPo idListPo) {
        return R.run(() -> menuService.removeByIds(idListPo.getIds()));
    }

    @Operation(summary = "批量更新所属应用")
    @PostMapping("batch-set-app")
    public R batchUpdateApp(@RequestBody SysMenuBatchSetAppPo batchSetAppPo) {
        return R.run(() -> menuService.batchSetApp(batchSetAppPo));
    }
}
